package com.huabo.contract.controller;


import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.hbfk.entity.DealUserToken;
import com.hbfk.entity.TblAttachment;
import com.hbfk.entity.TblStaffUtil;
import com.hbfk.util.FtpUtil;
import com.hbfk.util.JsonBean;
import com.huabo.contract.oracle.entity.TblContractAppendixsigning;
import com.huabo.contract.oracle.entity.TblContractPlannode;
import com.huabo.contract.oracle.entity.TblContractSpnode;
import com.huabo.contract.oracle.entity.TblCyhwProjectbudget;
import com.huabo.contract.oracle.entity.TblCyhwUnit;
import com.huabo.contract.service.TblContractAppendixsigningService;
import com.huabo.contract.service.TblContractCollectionService;
import com.huabo.contract.service.TblContractPaymenService;
import com.huabo.contract.service.TblContractPlannodeService;
import com.huabo.contract.service.TblContractSpnodeService;
import com.huabo.contract.service.TblCyhwProjectbudgetService;
import com.huabo.contract.service.TblCyhwUnitService;
import com.huabo.contract.service.TblFundPoolService;
import com.huabo.contract.service.TblInvestmentProjectService;
import com.huabo.contract.util.Tree;

import cn.hutool.json.JSONArray;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;

import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.DatatypeConverter;

import java.io.*;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@Slf4j
@Api(value="中船接口Controller",tags={"中船内控合同管理信息同步"})
public class ZcSynchronizationController {
	private static final Log logger = LogFactory.getLog(ZcSynchronizationController.class);
	public static ResourceBundle ncc = ResourceBundle.getBundle("setting/zcncc");

	@Resource
	private TblCyhwProjectbudgetService projectbudgetService;
	
	@Resource
	private TblFundPoolService  tblFundPoolService;

	@Resource
	private TblInvestmentProjectService tblInvestmentProjectService;
	//合同表
	@Resource
	private TblCyhwUnitService tblCyhwUnitService;
	//合同履行阶段
	@Resource
	private TblContractPlannodeService tblContractPlannodeService;
	
	//合同履行审批
	@Resource
	private TblContractSpnodeService tblContractSpnodeService;
	//收款单
	@Resource
	private  TblContractCollectionService tblContractCollectionService;
	
	//付款单
	@Resource
	private TblContractPaymenService tblContractPaymentServic;
	
	@Resource
	private TblCyhwProjectbudgetService tblCyhwProjectbudgetService;
	/*
	 * 相对方信息接口同步
	 * @param request
	 * startDate 起始时间，时间戳，获取创建时间从开始时间（>=）后的相对方信息,为空获取所有
	 * orgId 公司主键标识，获取相应公司的相对方数据，为空获取所有
	 * */
	@RequestMapping(value = "/synchronization/oppsiteInfo/getList", produces = "application/json; charset=utf-8",method = {RequestMethod.GET})
	@ApiOperation(value="相对方信息接口同步")
	public @ResponseBody String oppsiteInfogetList(@ApiParam(name="startDate",value="起始时间，时间戳",required=false) String startDate,
		 @ApiParam(name="orgId",value="公司主键标识",required=false)String orgId) throws Exception {
		String json = "";
		JSONObject obj=new JSONObject();
		 String date=null;
		try {
			Date date2 = new Date();
			long times = date2.getTime();
			System.out.println(times);
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
			if(!StringUtils.isEmpty(startDate)){
				Long l=new Long(startDate);
				Date d=new Date(l);
				date=sdf.format(d);
			}
			Map<String, Object> map=projectbudgetService.getList(date, orgId.trim().replace("\"\"", ""));
			
 		    json = JSONObject.toJSONString(map);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return json;
	}
	
	
	/*
	 * 投资项目档案接口信息同步
	 * add table TBL_INVESTMENT_PROJECT
	 * @param request
	 * operaType	Integer	  操作类型 0 -新增、1-修改
	 * data	  Json	存放保存数据
	 * */
	@RequestMapping(value = "/synchronization/investmentProject/addOrSave", produces = "application/json; charset=utf-8",method = {RequestMethod.POST})
	@ApiOperation(value="投资项目档案接口信息同步")
	public @ResponseBody String investmentProject(@ApiParam(name="operaType",value="操作类型",required=false) int operaType,
		 @ApiParam(name="data",value="存放保存数据",required=false)String data) throws Exception {
		Map<String, Object> resultMap =new HashMap<String, Object>();
		try {
			net.sf.json.JSONObject o=net.sf.json.JSONObject.fromObject(data);
			net.sf.json.JSONArray arr= (net.sf.json.JSONArray) o.get("tlist");
					for(Object j:arr){
						net.sf.json.JSONObject obj=(net.sf.json.JSONObject) j;
						tblInvestmentProjectService.saveTblInvestmentProject(obj.get("projectId").toString(), obj.get("projectNo").toString(), obj.get("projectName").toString());
					}
				resultMap.put("code", "0");
				resultMap.put("msg", "访问成功");
		} catch (Exception e) {
			e.printStackTrace();
			resultMap.put("code", "1");
			resultMap.put("msg", "访问失败");
		}

		return resultMap.toString();
	}

	

	/*
	 * 3.基金库接口信息同步
	 * add table TBL_FUNDPOOL
	 * @param request
	 * operaType	Integer	  操作类型 0 -新增、1-修改
	 * data	  Json	存放保存数据
	 * */
	@RequestMapping(value = "/synchronization/fundPoolINfo/addOrSave", produces = "application/json; charset=utf-8",method = {RequestMethod.POST})
	@ApiOperation(value="基金库接口信息同步")
	public @ResponseBody String fundPoolINfo(@ApiParam(name="operaType",value="操作类型",required=false) int operaType,
			@ApiParam(name="data",value="存放保存数据",required=false)String data) throws Exception {
		Map<String, Object> resultMap =new HashMap<String, Object>();
		try {
			net.sf.json.JSONObject o=net.sf.json.JSONObject.fromObject(data);
			net.sf.json.JSONArray arr= (net.sf.json.JSONArray) o.get("tlist");
					for(Object j:arr){
						net.sf.json.JSONObject obj=(net.sf.json.JSONObject) j;
						tblFundPoolService.saveTblFundPool(obj.get("fundPoolId").toString(), obj.get("fundPoolNo").toString(), obj.get("fundPoolName").toString());
					}
				resultMap.put("code", "0");
				resultMap.put("msg", "访问成功");
		} catch (Exception e) {
			e.printStackTrace();
			resultMap.put("code", "1");
			resultMap.put("msg", "访问失败");
		}

		return resultMap.toString();
	}




	/*
	 * 4.用印生效合同信息接口同步
	 * table TBL_FUNDPOOL
	 * @param request
	 * -----------------------差"nopaymoney": 10000000		--合同未支付金额	
	 * */
	@RequestMapping(value = "/synchronization/contractInfo/getList", produces = "application/json; charset=utf-8",method = {RequestMethod.GET})
	@ApiOperation(value="用印生效合同信息接口同步")
	public @ResponseBody String contractInfogetList(@ApiParam(name="startDate",value="起始时间，时间戳",required=true) String startDate,
			 @ApiParam(name="orgId",value="公司主键标识",required=true)String orgId) throws Exception {
			String json = "";
			JSONObject obj=new JSONObject();
			 String date=null;
			try {
				SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
				if(!StringUtils.isEmpty(startDate)){
					Long l=new Long(startDate);
					Date d=new Date(l);
					date=sdf.format(d);
				}
				Map<String, Object> map=tblCyhwUnitService.oppsiteInfogetList(date, orgId);
				
	 		    json = JSONObject.toJSONString(map);
			} catch (Exception e) {
				e.printStackTrace();
			}

			return json;
		}



	/*
	 * 5.合同履行阶段信息接口同步
	 * contractId 合同信息主键  必填
	 *  ------------------------------------差"wfnodemoney":400000			--该履行阶段未付金额
	 * */
	@RequestMapping(value = "/synchronization/contractInfo/getPerformanceStageList", produces = "application/json; charset=utf-8",method = {RequestMethod.GET})
	@ApiOperation(value="合同履行阶段信息接口同步")
	public @ResponseBody String getPerformanceStageList(
			 @ApiParam(name="contractId",value="合同信息主键",required=true)Integer contractId) throws Exception {
			String json = "";
			JSONObject obj=new JSONObject();
			 String date=null;
			try {
				SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
				Map<String, Object> map=tblContractPlannodeService.findPlannodeListByContractId(contractId);
				
	 		    json = JSONObject.toJSONString(map);
			} catch (Exception e) {
				e.printStackTrace();
			}

			return json;
		}


	/*
	 * 6.合同附件接口同步
	 * contractId 合同信息主键  必填
	 *
	 * */
	@RequestMapping(value = "/synchronization/contractFjInfo/getList", produces = "application/json; charset=utf-8",method = {RequestMethod.GET})
	@ApiOperation(value="合同附件接口同步")
	public @ResponseBody String contractFjInfoGetList(@ApiParam(name="contractId",value="合同信息主键",required=true)Integer contractId) throws Exception {
			String json = "";
			JSONObject obj=new JSONObject();
			 String date=null;
			try {
				SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
				Map<String, Object> map=tblCyhwUnitService.contractFjInfo(contractId);
				
	 		    json = JSONObject.toJSONString(map);
			} catch (Exception e) {
				e.printStackTrace();
			}

			return json;
		}

	/*
	 * 7.合同审批单、合同用印单连接接口
	 * contractId 合同信息主键  必填
	 * */
	@RequestMapping(value = "/synchronization/connectInterfacr", produces = "application/json; charset=utf-8",method = {RequestMethod.GET})
	@ApiOperation(value="合同审批单、合同用印单连接接口")
	public @ResponseBody String connectInterfacr(	
			@ApiParam(name = "contractId", value = "合同信息主键", required = true) String contractId) throws Exception {
		Map<String, Object> resultMap = new HashMap<String, Object>(0);
		try {
			if (StringUtils.isEmpty(contractId)) {
				resultMap.put("code", "1");
				resultMap.put("msg", "失败！");
			} else {
				JSONObject obj = new JSONObject();
				//obj.put("approvalFormLink", "http://172.16.120.15:9000/contract/contractToDetail?model=htgl&flowname=HTGL002&flowId=622316&contractId=" + contractId+"&token="); // 合同审批单单据链接
				 obj.put("approvalFormLink", "http://172.16.120.15:9000/contract/htlsjc/to_sptzgl_info?model=htgl&flowname=HTGL002&flowId=622316&contractId=" + contractId+"&token="); // 合同审批单单据链接

				obj.put("sealSheetLink", "http://172.16.120.15:9000/contract/projectrBudgetToModify?model=htgl&flowId=622324&budgetId=" + contractId+"&token="); // 合同用印单单据链接
				resultMap.put("code", "0");
				resultMap.put("msg", "成功！");
				resultMap.put("data", obj);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

		return resultMap.toString();
	}

	
	
	/*
	 * 8.合同执行登记接口：
	 * contractId 合同信息主键  必填
	 *
	 * */
	@RequestMapping(value = "/synchronization/executeInformation/registraion", produces = "application/json; charset=utf-8",method = {RequestMethod.GET})
	@ApiOperation(value="合同执行登记接口")
	public @ResponseBody String registraion(
			@ApiParam(name = "data", value = "存放传入数据", required = true) String data) throws Exception {
		Map<String, Object> resultMap = new HashMap<String, Object>(0);
		try {
			if (StringUtils.isEmpty(data)) {
				resultMap.put("code", "1");
				resultMap.put("msg", "失败！");
			} else {
				net.sf.json.JSONObject o=net.sf.json.JSONObject.fromObject(data);
				net.sf.json.JSONArray arr= (net.sf.json.JSONArray) o.get("tlist");
			    resultMap =tblContractSpnodeService.setData(arr);
			}

		} catch (Exception e) {
			e.printStackTrace();
			resultMap.put("code", "1");
			resultMap.put("msg", "失败！");
		}
		return resultMap.toString();
	}
	
	/*
	 * 企业/自然人接口--
	 * 相对方审批通过状态为6进行推送
	 * HTTP请求方式	HTTPS-POST
	 * */
	public void enterpriseperson(TblCyhwProjectbudget  budget) throws Exception{
		org.apache.commons.httpclient.HttpClient client=new org.apache.commons.httpclient.HttpClient();
		org.apache.http.HttpResponse reponse=null;
		String result=null;
		try {
		 PostMethod postMethod=new PostMethod(ncc.getObject("enterpriseperson").toString());
		 com.alibaba.fastjson.JSONObject obj=new com.alibaba.fastjson.JSONObject();
		 obj.put("name", budget.getBudgetname().trim()); 
		 obj.put("category", "1");
		 obj.put("code", budget.getBudgetid()+"");
		postMethod.setRequestHeader("Content-Type","application/json");
		RequestEntity entity = new StringRequestEntity(obj.toString(),"application/json","UTF-8");
		postMethod.setRequestEntity(entity);
		  client.executeMethod(postMethod);
		  java.io.InputStream in = postMethod.getResponseBodyAsStream();
		//下面将stream转换为String
		StringBuffer sb = new StringBuffer();
		InputStreamReader isr = new InputStreamReader(in, "UTF-8");
		char[] b = new char[4096];
		for(int n; (n = isr.read(b)) != -1;) {
		            sb.append(new String(b, 0, n));
		        }
	    result = sb.toString();
	    System.out.println("相对方保存成功后推送OA数据："+result);
//	    net.sf.json.JSONObject j=net.sf.json.JSONObject.fromObject(result);
//	    if(Integer.valueOf(j.get("status").toString())==2){
//	    	  return JsonBean.success();
//	    	}else{
//	    		return JsonBean.error();
//	    	}
//	    	
	} catch (Exception e) {
		// TODO: handle exception
		e.printStackTrace();
	}
	}
	
	 
	/*
	 * 合同收付款单接口
	 * HTTP请求方式	HTTPS-POST
	 * type（必填）:BXD =报销单   JKD=借款单  SKJSD=收款结算单
	 * */
	@Scheduled(cron = "0 0 23 * * ?")
	public void  scheduledTaskPaymentInformation(){
		paymentInformation("SKJSD");
		paymentInformation("BXD");
		paymentInformation("JKD");
	}
	
	public String paymentInformation(String type){
		org.apache.commons.httpclient.HttpClient client=new org.apache.commons.httpclient.HttpClient();
		org.apache.http.HttpResponse reponse=null;
		String result=null;
		try {
		 String ids=tblContractCollectionService.getSkContractIds();
		 PostMethod postMethod=new PostMethod(ncc.getObject("paymenturl").toString());
		 com.alibaba.fastjson.JSONObject obj=new com.alibaba.fastjson.JSONObject();
		 obj.put("type", type);
		 String _id="";
		 if(ids!=null&&!StringUtils.isEmpty(ids)){
		 for(String id:ids.split(",")){
			 _id+="\""+id+"\",";
		 }
		  _id=_id.substring(0, _id.length()-1);
	     obj.put("contractIds", "["+_id+"]");
	     System.out.println(obj.toString());
		 postMethod.setRequestHeader("Content-Type","application/json");
		RequestEntity entity = new StringRequestEntity(obj.toString(),"application/json","UTF-8");
		postMethod.setRequestEntity(entity);
	    //base64位加密传递用户名密码
		//String encodeing=DatatypeConverter.printBase64Binary("testsj001:testsj001".getBytes("utf-8"));
		//postMethod.setRequestHeader("Authorization","Basic "+encodeing); //java.util.Base64.getUrlEncoder().encodeToString(("testsj001"+":"+"testsj001").getBytes("utf-8"))
		  client.executeMethod(postMethod);
		  java.io.InputStream in = postMethod.getResponseBodyAsStream();
		//下面将stream转换为String
		StringBuffer sb = new StringBuffer();
		InputStreamReader isr = new InputStreamReader(in, "UTF-8");
		char[] b = new char[4096];
		for(int n; (n = isr.read(b)) != -1;) {
		            sb.append(new String(b, 0, n));
		        }
	    result = sb.toString();
	    System.out.println(result);
	    net.sf.json.JSONObject j=net.sf.json.JSONObject.fromObject(result);
	    if(j.get("status").toString().equals("200")){
	    	net.sf.json.JSONArray arr= net.sf.json.JSONArray.fromObject(j.get("data"));
	    	if(type.equals("BXD")||type.equals("JKD")){ //BXD =报销单   JKD=借款单  
	    		tblContractPaymentServic.setData(arr,type);
	    	  }else if(type.equals("SKJSD")){ //SKJSD=收款结算单
	    		  tblContractCollectionService.setData(arr);
	    	  }
	    	  return JsonBean.success();
	    	}else{
	    		return JsonBean.error();
	    	}  
	   }
		 return JsonBean.success();
	} catch (Exception e) {
		// TODO: handle exception
		e.printStackTrace();
		return JsonBean.error(e.getMessage());
	}
	}
	
	
 	@RequestMapping(value = "/synchronization/enterpriseperson", produces = "application/json; charset=utf-8",method = {RequestMethod.GET})
 	@ApiOperation(value="相对方信息推送测试接口")
 	public void testenterpriseperson(@ApiParam(name="budgetid",value="相对方主键",required=true)Integer budgetid){
 		TblCyhwProjectbudget pro=tblCyhwProjectbudgetService.findBudgetid(budgetid);
 		try {
 			enterpriseperson(pro) ;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}  
 		
 	}
 	
	@RequestMapping(value = "/synchronization/collectionInformation/registraion", produces = "application/json; charset=utf-8",method = {RequestMethod.POST})
 	@ApiOperation(value="收付款接口1-测试")
	public @ResponseBody String collectionInformation(@ApiParam(name="type",value="收付款类型",required=true)String type){
 		return  paymentInformation(type) ;
 	}
	
	@RequestMapping(value = "/synchronization/collectionInformation/registraion2", produces = "application/json; charset=utf-8",method = {RequestMethod.POST})
 	@ApiOperation(value="收付款接口2-测试")
	public String test1(String result,String type){
		org.apache.commons.httpclient.HttpClient client=new org.apache.commons.httpclient.HttpClient();
		org.apache.http.HttpResponse reponse=null;
		try {
	    System.out.println(result);
	  //  net.sf.json.JSONObject j=net.sf.json.JSONObject.fromObject(result);
	   // if(Integer.valueOf(j.get("status").toString())==2){
	    	net.sf.json.JSONArray arr=net.sf.json.JSONArray.fromObject(result);
	    	 if(type.equals("BXD")||type.equals("JKD")){ //BXD =报销单   JKD=借款单  
	    		tblContractPaymentServic.setData(arr,type);
 	    	  }else if(type.equals("SKJSD")){ //SKJSD=收款结算单
 	    		  tblContractCollectionService.setData(arr);
 	    	  }
	    	  return JsonBean.success();
	    	 
	} catch (Exception e) {
		// TODO: handle exception
		e.printStackTrace();
		return JsonBean.error(e.getMessage());
	}
	}
}
